package com.bcx.wind.workflow.imp.cmd.repositorycmd.processconfigcmd;

import com.bcx.wind.workflow.entity.WindProcessConfig;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.pojo.Condition;
import com.bcx.wind.workflow.support.JsonHelper;

import java.util.List;

import static com.bcx.wind.workflow.message.ErrorCode.OPERATE_FAIL;
import static com.bcx.wind.workflow.message.ErrorCode.QUERY_EMPTY;

/**
 * 删除匹配规则配置命令
 *
 * @author zhanglei
 */
public class RemoveConditionConfigCommand implements Command<Integer> {
    /**
     * 配置ID
     */
    private String configId;

    /**
     * 业务参数配置键 集合
     */
    private List<String> keys;

    /**
     * 需要删除业务参数配置的 配置数据
     */
    private WindProcessConfig windProcessConfig;

    /**
     * 执行数据
     */
    private CommandContext commandContext;

    public RemoveConditionConfigCommand(String configId,List<String> keys){
        this.configId = configId;
        this.keys = keys;
    }

    @Override
    public Integer executor(CommandContext context) {
        try{
            this.commandContext = context;
            return this.execute();
        }catch (Exception e){
            commandContext.log(e);
            return null;
        }
    }

    private Integer execute(){
        //校验参数
        checkArgs();
        //删除
        int ret = remove();
        //更新缓存
        this.commandContext.getConfiguration().addProcessConfigCache(this.windProcessConfig.getProcessId(),
                this.windProcessConfig);
        return ret;
    }

    private int remove(){
        List<Condition> conditions =  this.windProcessConfig.conditions();
        for(String key : this.keys){
            conditions.removeIf(condition -> condition.getKey().equals(key));
        }
        this.windProcessConfig.setCondition(JsonHelper.toJson(conditions));
        return this.commandContext.access().updateProcessConfig(windProcessConfig);
    }


    private void checkArgs(){
        if(this.configId == null){
            WindError.error(OPERATE_FAIL,null,"processConfig","removeCondition","configId");
        }
        this.windProcessConfig = this.commandContext.access().getProcessConfigById(configId);
        if(this.windProcessConfig == null){
            WindError.error(QUERY_EMPTY,null,"processConfig",configId);
        }
        if(this.keys == null){
            WindError.error(OPERATE_FAIL,null,"processConfig","removeCondition","keys");
        }
    }
}
